package com.github.fuse.context;

import com.github.fuse.annotation.Default;
import com.github.fuse.annotation.Fuse;
import com.github.fuse.entity.AopExecute;
import com.github.fuse.exception.FuseException;
import com.github.fuse.handler.AbstractFuseHandler;
import com.github.fuse.handler.FuseHandler;
import com.github.limit.util.LimitUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.CollectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;

/**
 * @author: wangdejun
 * @create: 2019-10-17 19:45
 **/
@Slf4j
public class FuseContext {

    public Object start(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取方法参数值数组
        Object[] args = joinPoint.getArgs();
        //得到其方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        log.info("请求参数为{}", args);
        // 获取拦截的方法
        Method method = methodSignature.getMethod();

        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        Object target = joinPoint.getTarget();
        Class<?>[] parameterTypes = methodSignature.getParameterTypes();
        AopExecute aopExecute = new AopExecute(joinPoint, args, parameterTypes, target, method);
        List<Annotation> annotations = LimitUtils.filterAnnotation(declaredAnnotations, Fuse.class);
        Annotation annotation = null;
        if (annotations != null && annotations.size() >= 1) {
            if (annotations.size() > 1) {
                throw new RuntimeException("熔断不支持多个注解");
            }
            annotation = annotations.get(0);
        }


        FuseHandler handler = AbstractFuseHandler.getHandler(annotation);
        return handler.handler(aopExecute, annotation);

    }
}
